package com.vt.file.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.vt.common.base.ResultData;
import com.vt.common.base.RetCode;
import com.vt.common.dto.file.FileUploadResultDTO;
import com.vt.common.param.file.Base64UploadRequestParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;


@Slf4j
@Service
public class FastDFSClientService {

    @Autowired
    private FastFileStorageClient storageClient;
    @Value("${fdfs.filedomain}")
    private String filedomain;

    /**
     * 通过字符串上传文件
     * @param param
     * @return
     */
    public ResultData uploadFile(Base64UploadRequestParam param) {
        byte[] buff = Base64.decodeBase64(param.getContent());
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, param.getSuffix(), null);
        if(null != storePath && StringUtils.isNotEmpty(storePath.getFullPath())) {
            FileUploadResultDTO fileUploadResultDTO = new FileUploadResultDTO();
            fileUploadResultDTO.setPath(storePath.getFullPath());
            fileUploadResultDTO.setFiledomain(filedomain);
            return ResultData.ok(fileUploadResultDTO);
        } else {
            log.error("文件上传失败");
            return ResultData.failed(RetCode.FAILED);
        }
    }

    /**
     *
     * @param file
     * @return 文件形式上传
     */
    public ResultData multpart(MultipartFile file) {
        try {
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
            if(null != storePath && StringUtils.isNotEmpty(storePath.getFullPath())) {
                FileUploadResultDTO fileUploadResultDTO = new FileUploadResultDTO();
                fileUploadResultDTO.setName(file.getOriginalFilename());
                fileUploadResultDTO.setPath(storePath.getFullPath());
                fileUploadResultDTO.setFiledomain(filedomain);
                return ResultData.ok(fileUploadResultDTO);
            } else {
                log.error("文件上传失败");
                return ResultData.failed(RetCode.FAILED);
            }
        } catch (IOException e) {
            log.error("文件上传异常");
            return ResultData.failed(RetCode.EXCEPTION);
        }
    }
}
